package product;



import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.labels.CategoryItemLabelGenerator;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.DatasetRenderingOrder;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.GradientPaintTransformType;
import org.jfree.ui.HorizontalAlignment;
import org.jfree.ui.StandardGradientPaintTransformer;
import org.jfree.ui.TextAnchor;

public class ManagerChart {

	long data1, data2, data3, data4;//판매비, 생산비, 인건비, 총수익


	Connection conn;
	long pro[]=new long[12]; //수익값
	long sal[]=new long[12]; //판매값
	long salar[]=new long[12];//인건비 값
	long del[]=new long[12];
	String [] su = {"01","02","03","04","05","06","07","08","09","10","11","12"};



	public ManagerChart(Connection conn) {
		this.conn=conn;
	}

	public void total(String year){ 
		//총판매량
		for(int s=0;s<=11;s++){
			String sale="select nvl(sum(sa_price),0) from sale where sa_mod_date like '%"+year+"/"+su[s]+"%' ";
			try{
				PreparedStatement pstmt =conn.prepareStatement(sale);
				ResultSet rs = pstmt.executeQuery();
				//해당 년도에 대한 수익값이 저장된다.
				while(rs.next()){	
					sal[s] = rs.getLong(1);
				}
				rs.close();
				pstmt.close();

			}catch(Exception ex){
				ex.printStackTrace();
			}

		}
		//총인건비 
		for(int s=0;s<=11;s++){
			String salary="select sum(s_"+su[s]+") from salary where s_year = "+year ;
			try{
				PreparedStatement pstmt =conn.prepareStatement(salary);
				ResultSet rs = pstmt.executeQuery();

				//해당 년도에 대한 수익값이 저장된다.
				while(rs.next()){
					salar[s] = rs.getLong(1);
				}
				rs.close();
				pstmt.close();

			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
		//총자재비
		for(int s=0;s<=11;s++){
			String deliver="select nvl(sum(pro_price * ea),0) from  code inner join delivery on pro_code = code where nal like '%"+year+"/"+su[s]+"%'";
			try{
				PreparedStatement pstmt =conn.prepareStatement(deliver);
				ResultSet rs = pstmt.executeQuery();

				//해당 년도에 대한 수익값이 저장된다.
				while(rs.next()){
					del[s] = rs.getLong(1);
				}
				rs.close();
				pstmt.close();

			}catch(Exception ex){
				ex.printStackTrace();
			}

		}
		//총 수익량
		String profit="select * from profit where p_year ="+year+" ";
		
		try{
			PreparedStatement pstmt =conn.prepareStatement(profit);
			ResultSet rs = pstmt.executeQuery();

			//해당 년도에 대한 수익값이 저장된다.
			while(rs.next()){
				for(int i=0;i<12;i++){ 
					pro[i]=rs.getLong(i+3);
				}
			}
			rs.close();
			pstmt.close();
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	public JFreeChart getChart() {

		// 데이터 생성

		DefaultCategoryDataset dataset1 = new DefaultCategoryDataset();                // bar chart 1
		DefaultCategoryDataset dataset2 = new DefaultCategoryDataset();                // line chart 1
		DefaultCategoryDataset dataset12 = new DefaultCategoryDataset();         // bar chart 2
		String[] name = {"판매량", "생산비", "인건비", "총수익"};

		// 데이터 입력 ( 값, 범례, 카테고리 )

		// 그래프 1        

		//1분기
		int bungi=1;
		for(int i=0;i<=9;i+=3){

			

			long sale= (sal[i]+sal[i+1]+sal[i+2])/1000;
			long p = (del[i]+del[i+1]+del[i+2])/1000;
			long salary = (salar[i]+salar[i+1]+salar[i+2])/1000;
			long pr = (pro[i]+pro[i+1]+pro[i+2])/1000; 

			dataset1.addValue(sale, name[0]+"(천원)", bungi+"분기");
			dataset1.addValue(p, name[1]+"(천원)",  bungi+"분기");
			dataset1.addValue(salary, name[2]+"(천원)",  bungi+"분기");
			//dataset1.addValue(pr, name[3],  bungi+"분기");


			dataset2.addValue(pr, name[3], bungi+"분기");
			dataset2.addValue(pr, name[3], bungi+"분기");
			dataset2.addValue(pr, name[3], bungi+"분기");
			dataset2.addValue(pr, name[3], bungi+"분기");

			bungi++;



		}



		for(int i=0;i<12;i++){

			pro[i]=0; //수익값
			sal[i]=0; //판매값
			salar[i]=0;//인건비 값
			del[i]=0;
		}





		// 렌더링 생성 및 세팅

		// 렌더링 생성

		final BarRenderer renderer = new BarRenderer();

		final BarRenderer renderer12 = new BarRenderer();

		final LineAndShapeRenderer renderer2 = new LineAndShapeRenderer();




		// 공통 옵션 정의

		final CategoryItemLabelGenerator generator = new StandardCategoryItemLabelGenerator();

		final ItemLabelPosition p_center = new ItemLabelPosition(

				ItemLabelAnchor.CENTER, TextAnchor.CENTER 

				);

		final ItemLabelPosition p_below = new ItemLabelPosition(

				ItemLabelAnchor.OUTSIDE6, TextAnchor.TOP_LEFT

				);

		Font f = new Font("Gulim", Font.BOLD, 14);

		Font axisF = new Font("Gulim", Font.PLAIN, 14);




		// 렌더링 세팅

		// 그래프 1

		renderer.setBaseItemLabelGenerator(generator);

		renderer.setBaseItemLabelsVisible(true);

		renderer.setBasePositiveItemLabelPosition(p_center);

		//renderer.setBaseItemLabelFont(f);

		        renderer.setGradientPaintTransformer(new StandardGradientPaintTransformer(

		                GradientPaintTransformType.VERTICAL));

		       renderer.setSeriesPaint(0, new GradientPaint(1.0f, 1.0f, Color.white, 0.0f, 0.0f, Color.blue));

		renderer.setSeriesPaint(0, new Color(0,162,255));



		// 그래프 2        

//		renderer12.setSeriesPaint(0, new Color(232,168,255));
//
//		//renderer12.setBaseItemLabelFont(f);
//
//		renderer12.setBasePositiveItemLabelPosition(p_center);
//
//		renderer12.setBaseItemLabelGenerator(generator);
//
//		renderer12.setBaseItemLabelsVisible(true);


		// 그래프 3        
		renderer2.setBaseItemLabelGenerator(generator);

		renderer2.setBaseItemLabelsVisible(true);

		renderer2.setBaseShapesVisible(true);

		renderer2.setDrawOutlines(true);

		renderer2.setUseFillPaint(true);

		renderer2.setBaseFillPaint(Color.WHITE); 

		renderer2.setBaseItemLabelFont(f);

		renderer2.setBasePositiveItemLabelPosition(p_below);

		renderer2.setSeriesPaint(0,new Color(219,121,22));

		renderer2.setSeriesStroke(0,new BasicStroke(

				2.0f,

				BasicStroke.CAP_ROUND,

				BasicStroke.JOIN_ROUND,

				3.0f)

				);




		// plot 생성
		final CategoryPlot plot = new CategoryPlot();



		// plot 에 데이터 적재
		plot.setDataset(dataset1);

		plot.setRenderer(renderer);

		plot.setDataset(1,dataset12);

		plot.setRenderer(1,renderer12);

		plot.setDataset(2, dataset2);

		plot.setRenderer(2, renderer2);




		// plot 기본 설정

		plot.setOrientation(PlotOrientation.VERTICAL);             // 그래프 표시 방향

		plot.setRangeGridlinesVisible(true);                       // X축 가이드 라인 표시여부

		plot.setDomainGridlinesVisible(true);                      // Y축 가이드 라인 표시여부



		// 렌더링 순서 정의 : dataset 등록 순서대로 렌더링 ( 즉, 먼저 등록한게 아래로 깔림 )

		plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);



		// X축 세팅

		plot.setDomainAxis(new CategoryAxis());              // X축 종류 설정

		plot.getDomainAxis().setTickLabelFont(axisF); // X축 눈금라벨 폰트 조정

		plot.getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions.STANDARD);       // 카테고리 라벨 위치 조정



		// Y축 세팅

		plot.setRangeAxis(new NumberAxis());                 // Y축 종류 설정

		plot.getRangeAxis().setTickLabelFont(axisF);  // Y축 눈금라벨 폰트 조정



		// 세팅된 plot을 바탕으로 chart 생성

		final JFreeChart chart = new JFreeChart(plot);

		chart.setTitle("순이익 그래프"); // 차트 타이틀

		TextTitle copyright = new TextTitle("      (단위 : 천원)", new Font("SansSerif", Font.PLAIN, 12));

		copyright.setHorizontalAlignment(HorizontalAlignment.LEFT);

		chart.addSubtitle(copyright);  // 차트 서브 타이틀

		return chart;

	}

}
